#define _CRT_SECURE_NO_WARNINGS

#include "ALL.h"

void PrintArray(int* a, int n)
{
	assert(a);

	for (int i = 0; i < n; i++) printf("%d ", a[i]);
	printf("\n");
}

void swap(int* a, int* b)
{
	int tmp = *a;
	*a = *b;
	*b = tmp;
}

void InsertSort(int* a, int n)
{
	assert(a);

	for (int i = 1; i < n; i++)
	{
		int end = i - 1;
		int tmp = a[i];
		while (end >= 0)
		{
			if (a[end] > tmp)
			{
				a[end + 1] = a[end];
				end--;
			}
			else break;
		}
		a[end + 1] = tmp;
	}
}

void SherSort(int* a, int n)
{
	assert(a);

	int gap = n;
	while (gap > 1)
	{
		gap /= 2;
		for (int i = 0; i < n - gap; i++)
		{
			int end = i;
			int tmp = a[i + gap];
			while (end >= 0)
			{
				if (a[end] > tmp)
				{
					a[end + gap] = a[end];
					end -= gap;
				}
				else break;
			}
			a[end + gap] = tmp;
		}
	}
}

void SelectSort(int* a, int n)
{
	assert(a);

	int left = 0, right = n - 1;
	while (left < right)
	{
		int mini = left, maxi = left;
		for (int i = left; i <= right; i++)
		{
			if (a[i] > a[maxi]) maxi = i;
			if (a[i] < a[mini]) mini = i;
		}
		swap(&a[left], &a[mini]);
		if (maxi == left) maxi = mini;
		swap(&a[right], &a[maxi]);

		left++;
		right--;
	}
}

void adjustdown(int* a, int n, int parent)
{
	int child = parent * 2 + 1;
	while (child < n)
	{
		if (child + 1 < n && a[child] < a[child + 1]) child++;
		if (a[child] > a[parent])
		{
			swap(&a[child], &a[parent]);
			parent = child;
			child = parent * 2 + 1;
		}
		else break;
	}
}
void HeapSort(int* a, int n)
{
	assert(a);

	for (int i = (n - 2) / 2; i >= 0; i--) adjustdown(a, n, i);

	int end = n - 1;
	while (end > 0)
	{
		swap(&a[0], &a[end]);
		adjustdown(a, end, 0);
		end--;
	}
}

void BubbleSort(int* a, int n)
{
	assert(a);

	for (int i = 0; i < n; i++)
	{
		bool flag = true;
		for (int j = 1; j < n - i; j++)
		{
			if (a[j - 1] > a[j])
			{
				swap(&a[j - 1], &a[j]);
				flag = false;
			}
		}
		if (flag) break;
	}
}

int mid_num(int* a, int l, int r)
{
	int mid = (l + r) / 2;
	if (a[l] > a[r])
	{
		if (a[r] > a[mid]) return r;
		else if (a[l] < a[mid]) return l;
		else return mid;
	}
	else
	{
		if (a[l] > a[mid]) return l;
		else if (a[r] < a[mid]) return r;
		else return mid;
	}
}
void QuickSort(int* a, int left, int right)
{
	if (left >= right) return;

	int mid = mid_num(a, left, right);
	swap(&a[left], &a[mid]);
	int keyi = left, begin = left, end = right;

	while (begin < end)
	{
		while (begin < end && a[end] >= a[keyi]) end--;
		while (begin < end && a[begin] <= a[keyi]) begin++;

		swap(&a[begin], &a[end]);
	}
	swap(&a[keyi], &a[begin]);

	QuickSort(a, left, begin - 1);
	QuickSort(a, begin + 1, right);
}
